package com.wyl.template.controller;

import com.wyl.template.aop.annotation.SysLogger;
import com.wyl.template.domain.common.ResponseResult;
import com.wyl.template.domain.dto.UserRoleDTO;
import com.wyl.template.domain.model.SysUserDO;
import com.wyl.template.domain.request.UserLoginRequest;
import com.wyl.template.enums.LoggerType;
import com.wyl.template.exception.ErrorCodeEnum;
import com.wyl.template.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Auther: wyl
 * @Date: 2021/6/11
 * @Description: 可以公开访问的controller层
 */
@SysLogger(group = "公开模块")
@RestController
@RequestMapping("/pub")
@Slf4j
public class PublicController extends BaseController<SysUserService, SysUserDO> {

    @Autowired
    private SysUserService userService;

    @RequestMapping("need_login")
    public ResponseResult needLogin() {
        return ResponseResult.error("温馨提示：请使用对应的账号登录");
    }

    @RequestMapping("not_permit")
    public ResponseResult notPermit(){

        return ResponseResult.error("温馨提示：拒绝访问，没权限");
    }

    @SysLogger(name = "登录", type = LoggerType.SELECT)
    @PostMapping("login")
    public ResponseResult login(@RequestBody UserLoginRequest user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try{
            subject.login(usernamePasswordToken);
        }catch (Exception e){
            return ResponseResult.error(ErrorCodeEnum.USER_LOGIN_ERR);
        }
        //获得登录成功的用户信息
        SysUserDO userDO = (SysUserDO) subject.getPrincipal();

        //更新用户登录时间
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setId(userDO.getId());
        userRoleDTO.setLastLoginTime(new Date());
        userService.updateUser(userRoleDTO);

        return ResponseResult.success(userDO.getUserName());
    }

}
